package com.example.multiReactorMultiThread;

import lombok.Getter;
import lombok.SneakyThrows;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;

public class SubReactor implements Runnable {


    private Selector selector;

    public SubReactor() throws IOException {
        this.selector = Selector.open();
    }

    @SneakyThrows
    @Override
    public void run() {
        while (!Thread.interrupted()) {
            selector.select();
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                Handler handler = (Handler) selectionKey.attachment();
                handler.setSelectionKey(selectionKey);
                handler.run();
                iterator.remove();
            }
        }
    }


    public void registry(Handler handler) throws IOException {
        SocketChannel socketChannel = handler.getSocketChannel();
        socketChannel.configureBlocking(false);
        socketChannel.register(selector, SelectionKey.OP_READ, handler);
    }
}
